<template>
  
  <div style="flex: 90%;width: 500px; margin-left: 20px;">

    <el-dialog v-model="dialogTableVisible" title="审核条件" width="800" style="width:100%;height:100%;margin: 0;">
        <el-table :data="tableRefCondition">
          <el-table-column property="indicator" label="指标" width="150" />
          <el-table-column property="condition" label="审核条件" width="200" />
          <el-table-column prop="x" label="是否通过"  width="150">
              <template #default="scope">
                <div class="button-container">
                  <el-button type="warning" circle size="small" v-show="shouldShowButton(scope.row, 0)" style="margin-left:12px">待</el-button>
                  <el-button type="danger" :icon="CloseBold" circle size="small" v-show="shouldShowButton(scope.row, 2)"/>               
                  <el-button type="success" :icon="Check" circle size="small" v-show="shouldShowButton(scope.row, 1)"/>
                </div>
              </template>
          </el-table-column>
          <el-table-column prop="审核" label="审核" width="120">
            <template #default="scope">
              <el-select @change="handleConditionIsOk(scope.row, $event)"  v-model="[ '待确定', '通过' ,  '不通过'][scope.row.isOk]" placeholder="Select" size="small" class="select" >
                <el-option v-for="item in condition_sh_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>  
          </el-table-column>
        <el-table-column property="规则" label="规则" width="200">

        </el-table-column>
        <el-table-column property="审核理由" label="审核理由" width="800">
          <template #default="scope">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="scope.row.description"
            >
            </el-input>
        </template>
        </el-table-column>
        </el-table>
      </el-dialog>

    <el-dialog v-model="eidtDialogTableVisible" title="编辑" width="1000" >
        <div style="display: flex;">
          <p style="width:80px">概念</p>
          <el-input 
              style="display: flex;width:300px"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="data.tip"
              @update:model-value="onInputChange_Tip">
            </el-input>

          <p style="width:120px">涨跌原因</p>
          <el-input 
              style="display: flex;width:300px"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="data.note"
              @update:model-value="onInputChange_UpDownReason">
            </el-input>

            <p style="width:120px">逻辑分析</p>
            <el-input 
              type="textarea"
              :rows="10"
              placeholder="请输入内容"
              v-model="data.strB"
              @update:model-value="onInputChange_Logic">
            </el-input>  
        </div>
      </el-dialog>

    <el-form :inline="true" :model="data" class="demo-form-inline">
        <el-form-item label="股票代码">
        <el-input
            v-model="data.name"
            style="width: 240px"
            placeholder="input stock code"
            @update:model-value="onInputChange"
        /></el-form-item>
        <el-form-item>
          <el-button type="primary" @click="clickLoadZhiShu()">加载指数</el-button>
        </el-form-item>
    </el-form>

    <el-table
      :data="tableName"
      style="width: 100%;"
      v-show="data.isTableVisible"
    >
      <el-table-column prop="name" label="名称" width="200" />
      <el-table-column prop="tscode" label="代码" width="180" />
      <el-table-column prop="tscode" label="操作" width="360" > 
        <template #default="scope">
          <el-button @click="onSubmit_addRecordData(scope.row)" type="primary" >
              添加数据
          </el-button>
          <el-input v-model="scope.row.rid" placeholder="请输入rid" style="width:80px;margin-left:20px;margin-right: 20px;"></el-input>
          <el-button @click="onSubmit_addTiggerData(scope.row)" type="primary" >
              添加龙虎榜
          </el-button>
        </template>  
      </el-table-column>
      <el-table-column prop="type" label="类型" width="180">
        <template #default="scope">
          <el-select @change="handleType(scope.row, $event)"  v-model="[ '请选择',  '市场情绪龙', '市场趋势龙' ,'板块情绪龙' ,'板块趋势龙' ,'板块领涨龙' ,
 '市场老龙' , '板块老龙' ,'权重老龙' , '预期龙' , '避险龙', '杂毛' ][scope.row.shortNameType]" placeholder="Select" size="small" class="select" >
            <el-option v-for="item in options_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>  
      </el-table-column>
      <el-table-column prop="importantScore" label="权重" width="180">
        <template #default="scope">
          <el-select @change="handleScore(scope.row, $event)"  v-model="[ '0.5级', '1级',  '2级', '3级' ,'4级' ,'5级' ][scope.row.importantScore]" placeholder="Select" size="small" class="select" >
            <el-option v-for="item in score_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>  
      </el-table-column>
    </el-table>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="选日期">
          <el-date-picker
                  v-model="data.dateTime"
                  type="date"
                  placeholder="Pick a day"
                  size="large"
                  @change="handleDateChange"
              />
        </el-form-item>
        <el-form-item>
          <el-select @change="handleIndustry($event)"  v-model="industryType" placeholder="Select" size="large" class="select">
            <el-option v-for="item in options_industry" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLoadScore">刷新</el-button>
        </el-form-item>
    </el-form>

    <el-table
        v-loading="loading"
        ref="tableRef"
        row-key="code"
        :data="tableDataScore"
        style="width: 100%;" class="custom-border"
        @sort-change="handleSortChange"
      >
      <el-table-column prop="orderIndex" label="序号" sortable="custom" :width="50" fixed>
            <template #default="scope">
                <el-text >{{scope.$index + 1}}</el-text>
            </template>
        </el-table-column>

        <el-table-column style="color: #990000;" prop="tip" label="一二级行业" :width="100" fixed>
            <template #default="scope">
                <el-text style="color:#E6A23C;font-weight: bold;font-size: 13px;">{{scope.row.tip}}</el-text>
            </template>
        </el-table-column>

        <el-table-column prop="orderIndex" label="名称" sortable="custom" :width="110" fixed>
            <template #default="scope">
                <el-text @mouseover="handleMouseOver(scope.row)">{{scope.row.name}}</el-text>
            </template>
        </el-table-column>
        
        <el-table-column prop="open" label="今开盘" sortable="custom" :width="labWidthChange" >
            <template #default="scope">
                <el-text :style="{color:getIncreaseTextColorCkOpenClose(scope.row.open, scope.row.ckTodayOpen)}">{{getIncreaseData(scope.row.open, scope.row.ckTodayOpen)}}</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="close" label="今收盘" sortable="custom" :width="labWidthChange" >
            <template #default="scope">
                <el-text :style="{color:getIncreaseTextColorCkOpenClose(scope.row.close, scope.row.ckTodayClose)}">{{getIncreaseData(scope.row.close, scope.row.ckTodayClose)}}</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="increase" label="涨跌分析" width="168" >
          <template #default="scope">
                <el-text  style="color:#E6A23C;font-weight: bold">{{scope.row.note}}</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="increase" label="竞价压力" :width="labWidthChange" >
            <template #default="scope">
                <el-text >{{getStressScore_Yes_str(scope.row)}}</el-text>
            </template>
        </el-table-column>
        
        <el-table-column prop="increase" label="操作" :width="280" >
            <template #default="scope">
              <el-button @click="handleCondition(scope.row)" type="primary" plain>
                审核条件
              </el-button>
              <el-button @click="handleEdit(scope.row)" type="primary" plain>
                编辑
              </el-button>
              <el-button @click="onLoadTigger(scope.row)" type="primary" plain v-if="shouldShowButtonTigger(scope.row)">
                龙虎榜
              </el-button>
            </template>
        </el-table-column>
        <el-table-column prop="importantScore" label="权重" width="100">
          <template #default="scope">
            <el-select @change="handleScore(scope.row, $event)"  v-model="[ '0级', '1级',  '2级', '3级' ,'4级' ,'5级' ][scope.row.stressScore]" placeholder="Select" class="select" >
              <el-option v-for="item in score_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </template>  
        </el-table-column>
        <el-table-column prop="increase" label="备注" width="auto" >
          <el-text >{{''}}</el-text>
        </el-table-column>

      </el-table>  


  </div>
</template>

<script>
import Sortable from 'sortablejs';
import axios from "axios";

export default {
  data() {
    return {
      data:{
        code: "",
        name: "",
        isTableVisible:false,
        dateTime: "",
        note:"",
        tip:"",
        strB:"",
        id:0,
        isSelected:true,
      },
      labWidth:70,
      labWidthChange:80,
      loading:false,
      score_type : [
                { value: '5',label: '5级', },
                { value: '4',label: '4级', },
                { value: '3',label: '3级' },

                { value: '2',label: '2级' },
                { value: '1',label: '1级' },
                { value: '0',label: '0级' },
            ],
      condition_sh_type : [
                { value: '2',label: '不通过' },
                { value: '1',label: '通过' },
                { value: '0',label: '待确定' },
            ],
            options_type :  [
                { value: '1',label: '杂毛', },
                { value: '2',label: '市场情绪龙', },
                { value: '3',label: '市场趋势龙' },

                { value: '4',label: '板块情绪龙' },
                { value: '5',label: '板块趋势龙' },
                { value: '6',label: '板块领涨龙' },

                { value: '7',label: '市场老龙' },
                { value: '8',label: '板块老龙' },
                { value: '9',label: '权重老龙' },
                
                { value: '10',label: '预期龙' },
                { value: '11',label: '避险龙' },
            ],      
      tableRefCondition:[],
      tableDataScore:[],
      tableDataTigger : [],
      dialogKlineVisible : false,
      dialogTableVisible : false,
      eidtDialogTableVisible : false,
      tiggerDialogTableVisible : false,

      tableName: [],

      stressScore:0,
      industryType: "短线",
      options_industry : [
                    { value: 'A股指数' },
                    { value: '同花顺行业板块' },
                    { value: '同花顺概念' },
                    { value: '同花顺概念第2天' },
                    { value: '同花顺热门板块' },
                    { value: 'ETF' },
                    { value: 'ETF第2天' },
                    { value: '情绪' },
                    { value: '短线' },
                    { value: '第2天入场' },
                    { value: '第3天出场' },
                    {value:'龙虎榜'},
                    { value: '龙虎榜第2天' },
                    { value: '东方财富热榜' },
                    { value: '同花顺热榜' },
                    { value: '涨停容量榜' },
                    { value: '负反馈榜' },
                    { value: '今日涨停板' },
                    { value: '涨停板第2天' },  
                    { value: '涨停板第3天' },  
                    { value: '港股' },
                    { value: '美股' },
                    { value: '中概美股' },
                ],      
    };
  },

  mounted() {
    // this.initSortable();
    document.title = "短线";
    this.data.dateTime = this.getToday();
    this.initSortable();
  },
  methods: {
    // initSortable() {
    //   const table = this.$refs.table; // 获取 el-table 的 DOM 元素
    //   const tbody = table.$el.querySelector('.el-table__body-wrapper tbody');

    //   Sortable.create(tbody, {
    //     animation: 150, // 动画时长
    //     onEnd: (evt) => {
    //       const { oldIndex, newIndex } = evt; // 获取拖拽前后的索引
    //       const movedRow = this.tableData.splice(oldIndex, 1)[0]; // 移除被拖拽的行
    //       this.tableData.splice(newIndex, 0, movedRow); // 插入到新位置
    //     },
    //   });
    // },

    onInputChange(newValue, oldValue) {
      console.log("Input changed:", newValue);
      const containsChinese = /[\u4e00-\u9fa5]/.test(newValue);
      if (newValue === '') {
        this.data.isTableVisible = false;
      } else {
        this.data.isTableVisible = true;
        if (containsChinese) {
          this.onSearh(newValue, 2);
        } else if (newValue.length == 6) {
          this.onSearh(newValue, 1);
        }
      }
    },

    onSearh(str, type){
      console.log("submit!");
      const encodedName = encodeURIComponent(str);
      const api = "api/plat/stockNowPrice/getStockListByName?name=" + encodedName;
      console.log(api) 
      axios
        .get(api)
        .then((response) => {
          this.tableName = response.data.data;
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    },

    handleDateChange(val) {
        console.log('选择了新的日期/时间:', val);
        const date = new Date(val)
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要加1
        const day = ('0' + date.getDate()).slice(-2);
        const dayTime = `${year}-${month}-${day}`;
        console.log('选择了新的日期/时间:', dayTime);
        const date1 = new Date(this.getToday());
        const date2 = new Date(dayTime);

        if (date1 < date2) {
          ElMessage({
            message: "日期不能晚于今天",
            type: "error",
          });
          return;
        }
        this.data.dateTime = dayTime;
        this.onLoadScore();
    },

    getToday(){
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
      const day = String(today.getDate()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    },

    handleIndustry(value) {
      this.industryType = value;
      this.onLoadScore();
    },

    onLoadScore()  {
      console.log("submit!");
      const api = "api/plat/stockDayRecord/findPageList1/1/100?recordDate=" + this.data.dateTime + "&strA=" + encodeURIComponent(this.industryType);
      console.log(api) 
      axios
        .get(api)
        .then((response) => {
          this.tableDataScore = response.data.data.list;
          var list = response.data.data.list;
          console("返回结果：" + this.tableDataScore)
          this.stressScore = 0;
          for (var i = 0; i < list.length; i++) {
            // this.stressScore.value = this.stressScore.value + getStressScore_Yes(list[i]);
            // console.log("分数：" + stressScore.value);
          }
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    },

    getIncreaseTextColorCkOpenClose (value, ckOpenClose) {
      if (ckOpenClose === 0) {
        return '#333333'; 
      }
      if (value <= -9.90) {
        return 'green'; 
      } else {
        if (value <= 0 && value > -9.90) {
          return 'green'; 
        } else {
          if (value < 9.90 && value > 0) {
            return '#F56C6C'; 
          } else {
            return 'red';
          }
        }
      }
    },

    getIncreaseData(increase, ckOpenClose) {
        if (ckOpenClose === 1) {
          return increase + "%";
        } else { 
          return "--";  
        }
    },

    getStressScore_Yes_str(row){
      var xs = this.getStressScore_Yes(row);
      if (xs >= 3) {
        return '' + xs;
      }
      return ''; 
    },

    getStressScore_Yes(row) {
      var xs = 0.00;  
      if (row.bidding <= 8 && row.bidding > 5) {
        xs = 1;
      }
      if (row.bidding <= 9.90 && row.yestoday > 8) {
        xs = 2;
      }
      if (row.bidding > 9.90) {
        xs = 3;
      }
      xs = xs * row.stressScore / 3.00;// 昨天的乘以60%
      return xs; 
    },

    handleScore(row, value) {
      this.onUpdate({
        id: row.id,
        stressScore: value,
      })
      setTimeout(() => {
            console.log('延迟执行的代码');
            // 在这里执行你需要延迟的操作
            this.onLoadScore();
          }, 200); // 延迟2秒执行
    },

    onUpdate(params) {
      console.log("submit!" + params);
     
      axios
        .put("api/plat/stockDayRecord/update", params)
        .then((response) => {
          // console.log(response.status);
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    },

    onUpdateIndicatorOk(params) {
      console.log("submit!" + params);
      axios
        .put("api/plat/stockIndicatorOk/update", params)
        .then((response) => {
          // console.log(response.status);
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    },

    handleCondition(row){
      this.dialogTableVisible = true;
      this.onLoadCondition();
    },

    handleEdit(row){
      this.data.id = row.id;
      this.eidtDialogTableVisible = true;
      this.data.note = row.note;
      this.data.tip = row.tip;
      this.data.strB = row.strB;
    },

    onLoadTigger(row) {
    // console.log("submit!");
    // const api = "api/plat/stockTigger/findPageList/1/50?dayTime=" + data.dateTime + "&code=" + data.code;
    // console.log(api) 
    // axios
    //   .get(api)
    //   .then((response) => {
    //     tableDataTigger.value = response.data.data.list; 
    //     tiggerDialogTableVisible.value = true;
    //   })
    //   .catch((error) => {
    //     console.error("Error fetching data:", error);
    //   });
  },

  shouldShowButtonTigger(row) {
    if (row.intA === 1) {
      return true;
    } else {
      return false;
    }
  },

  onSubmit_addRecordData(row){
    if(this.data.dateTime === '' || this.data.dateTime == null) {
      ElMessage({
            message: "请选择日期",
            type: "error",
          });
      return;
    }
    const api= "api/plat/stockDayRecord/adddRecordData?dayTime=" + this.data.dateTime + "&code=" + row.tscode + "&strA=" + encodeURIComponent(this.industryType);
    axios.get(api).then((response) => {
      console.log(response);
      if (response.data.status == 200) {
          ElMessage({
            message: "添加成功",
            type: "success",
          });
          onLoadScore();
        } else {
          ElMessage({
            message: response.data.message,
            type: "error",
          });
        }
    })
  },

  onSubmit_addTiggerData(row) {
    if(this.data.dateTime === '' || this.data.dateTime == null) {
      ElMessage({
            message: "请选择日期",
            type: "error",
          });
      return;
    }

    if (typeof row.rid === 'undefined') {
      ElMessage({
            message: "请输入rid",
            type: "error",
          });
      return;
    }  
    const api= "api/plat/stockTigger/addTiggerData?dayTime=" + this.data.dateTime + "&code=" + row.tscode + "&rid=" + row.rid + "&strA=" + encodeURIComponent(this.industryType);

    axios.get(api).then((response) => {
      console.log(response);
      if (response.data.status == 200) {
          ElMessage({
            message: "添加成功",
            type: "success",
          });
          this.onLoadScore();
        } else {
          ElMessage({
            message: response.data.message,
            type: "error",
          });
        }
    })
  },

  onInputChange_UpDownReason(newValue, oldValue) {
    console.log("Input changed:", newValue);
    this.onUpdate({
        id: this.data.id,
        note: newValue,
      })
      setTimeout(() => {
            console.log('延迟执行的代码');
            // 在这里执行你需要延迟的操作
            this.onLoadScore();
          }, 200); // 延迟2秒执行
  },

  onInputChange_Tip(newValue, oldValue) {
    console.log("Input changed:", newValue);
    this.onUpdate({
        id: this.data.id,
        tip: newValue,
      })
      setTimeout(() => {
            console.log('延迟执行的代码');
            // 在这里执行你需要延迟的操作
            this.onLoadScore();
          }, 200); // 延迟2秒执行
  },

  onInputChange_Logic(newValue, oldValue) {
    console.log("Input changed:", newValue);
    this.onUpdate({
        id: this.data.id,
        strB: newValue,
      })
      setTimeout(() => {
            console.log('延迟执行的代码');
            // 在这里执行你需要延迟的操作
            this.onLoadScore();
          }, 200); // 延迟2秒执行
  },

  initSortable() {
      const table = this.$refs.tableRef; // 获取 el-table 的 DOM 元素
      const tbody = table.$el.querySelector('.el-table__body-wrapper tbody');

      Sortable.create(tbody, {
        animation: 150, // 动画时长
        onEnd: (evt) => {
          const { oldIndex, newIndex } = evt; // 获取拖拽前后的索引
          const movedRow = this.tableDataScore.splice(oldIndex, 1)[0]; // 移除被拖拽的行
          this.tableDataScore.splice(newIndex, 0, movedRow); // 插入到新位置
        },
      });
    },

    shouldShowButton(row, value) {
      if (row.isOk == value) {
        return true;
      }
    },

    handleConditionIsOk(row, value) {
      this.onUpdateIndicatorOk({
        id: row.id,
        isOk: value,
      });
      setTimeout(() => {
            console.log('延迟执行的代码');
            // 在这里执行你需要延迟的操作
            this.onLoadCondition();
          }, 200); // 延迟2秒执行
    },

    onLoadCondition() {
      console.log("submit!");
      const api = "api/plat/stockIndicatorOk/findPageList/1/50?recordId=516860101";
      console.log(api) 
      axios
        .get(api)
        .then((response) => {
          this.tableRefCondition = response.data.data.list;
          this.dialogTableVisible = true;
          console.log(this.tableRefCondition);
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    },

    clickLoadZhiShu() {
      // 显示确认框
      ElMessageBox.confirm(
        '是否确认加载指数数据？', '加载指数数据',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning' // 弹窗类型，可以是 'success', 'info', 'warning', 'error'
        }).then(() => {
            this.onAddZhiShuRecord()
        }).catch(() => {
        
        });
      },

      onAddZhiShuRecord() {
        console.log("submit!");
        const api = "api/plat/stockDayRecord/loadZhishuData?dayTime=" + this.data.dateTime + "&strA=" + encodeURIComponent(this.industryType);
        console.log(api) 
        axios
          .get(api)
          .then((response) => {
            console.log(response);
        if (response.data.status == 200) {
            ElMessage({
              message: "添加成功",
              type: "success",
            });
          } else {
            ElMessage({
              message: response.data.message,
              type: "error",
            });
          }
          })
          .catch((error) => {
            console.error("Error fetching data:", error);
          });
        },




  },
};
</script>